import axios from "axios"
import { ElMessage } from 'element-plus'
import useStore from "@/store/job";
import router from "@/router/job";
import { getToken } from '@/utils/token'

// console.log('BASE_URL',import.meta.env.VITE_APP_BASE_URL);


const instance = axios.create({
//   baseURL: 'http://ibuy123.cn:8888',
  baseURL: '/api',
  timeout: 5000,
});
//请求拦截器 - 添加token
instance.interceptors.request.use(
  function (config) {
    // 从store获取token（优先使用主store的token）
    const token = getToken()
    if (token) {
      config.headers['token'] = token
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);
  //响应拦截器
instance.interceptors.response.use(function (response) {
  // 针对图片上传接口特殊处理
  if (response.config.url && response.config.url.includes('/upload')) {
    // 检查后端返回的完整响应格式
    if (response.data && response.data.code === 0 && response.data.data) {
      return Promise.resolve(response.data);
    } else {
      ElMessage.error('图片上传失败');
      return Promise.reject(response.data);
    }
  }
  const data=response.data
  if(data.code == 0){
    return Promise.resolve(data)
  }else{
    ElMessage.error(data.msg)
    return Promise.reject(data)
  }
}, function (error) {
    console.log('error',error);
    const response=error.request.response
    if (response) {
      const errorData = JSON.parse(response);
      if (errorData.message || errorData.msg) {
        ElMessage.error(errorData.message || errorData.msg);
      }
//系统强制退出(token失效，已经登出)
      if(errorData.code === 999){
        ElMessage.error('系统错误，请刷新页面')
      }
    }else{
      ElMessage.error('网络连接超时')
    }
    
    return Promise.reject(error);
  });

  export default instance